﻿#include "CBossModule.h"
#include "MsgID.h"
#include "MsgStruct.h"

#include "CUartSendModule.h"

#include <string.h>
#include <stdio.h>
#include <Windows.h>

extern int add_uart_log(int log_type, const char* data, int len);

#pragma warning(disable:4996)

static CUartSendModule uartSendMod;
static char uart_recv_in_buf[4096] = {0};
static int uart_recv_in_idx = 0;


static char _log_buf[1024] = {0};

#define CLINET_DEBUG_LOG(fmt, ...) { \
	memset(_log_buf, 0, sizeof(_log_buf)); \
	sprintf(_log_buf, "%s:%d fn:%s " fmt "\n", strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__, __LINE__, __FUNCTION__, __VA_ARGS__); \
	WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), _log_buf, strlen(_log_buf), NULL, NULL); \
}

static int ON_MODULE_MSG(CBossModule, MSG_ID_UART_SEND_REQ) {
	AS_MODULE(&uartSendMod)->sendMsg(AS_MODULE(&uartSendMod), msg); // just transfer
	return 0;
}

static int ON_MODULE_MSG(CBossModule, MSG_ID_START_UART_SEND) {
	AS_MODULE(&uartSendMod)->sendMsg(AS_MODULE(&uartSendMod), msg); // just transfer
	return 0;
}

static int ON_MODULE_MSG(CBossModule, MSG_ID_STOP_UART_SEND) {
	AS_MODULE(&uartSendMod)->sendMsg(AS_MODULE(&uartSendMod), msg); // just transfer
	return 0;
}

int get_uart_recv_data_len_from_lua() {
	return -1;
}

int notify_lua_uart_recv_done() {
	return 0;
}

static int ON_MODULE_MSG(CBossModule, MSG_ID_UART_RECV_1BYTE) {
	static int data_len = -1;
	ST_UART_RECV_1BYTE* param = (ST_UART_RECV_1BYTE*)msg;

	uart_recv_in_buf[uart_recv_in_idx++] = param->recv_1c;
	if (-1 == data_len) {
		data_len = get_uart_recv_data_len_from_lua();
	}
	
	if (-1 != data_len && uart_recv_in_idx == data_len) {
		add_uart_log(LOG_TYPE_UART_RECV_DONE, uart_recv_in_buf, uart_recv_in_idx);
		notify_lua_uart_recv_done();

		data_len = -1;
		uart_recv_in_idx = 0;
		memset(uart_recv_in_buf, 0, sizeof(uart_recv_in_buf));
	}
	return 0;
}

static int reg_func_on_msgid(CModule* thes) {
	REG_MODULE_MSG_FUNC(CBossModule, thes, MSG_ID_START_UART_SEND);
	REG_MODULE_MSG_FUNC(CBossModule, thes, MSG_ID_STOP_UART_SEND);	
	REG_MODULE_MSG_FUNC(CBossModule, thes, MSG_ID_UART_SEND_REQ);
	REG_MODULE_MSG_FUNC(CBossModule, thes, MSG_ID_UART_RECV_1BYTE);
	
    return 0;
}

int construct_boss_module(CBossModule* thes, const char* module_name) {
	construct_module(&thes->parent, module_name);
	reg_func_on_msgid(AS_MODULE(thes));

	construct_uart_send_module(&uartSendMod, "uart_send_module");

	AS_MODULE(thes)->run(AS_MODULE(thes), USE_DEFAULT_MODULE_ENTRY);
	return 0;
}

